/**
 *       Copyright (c) 2012 Lukas Zaruba
 *
 *   This file is part of Robot Playground.
 *
 *   Robot Playground is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU Lesser General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   Robot Playground is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU Lesser General Public License for more details.
 *
 *   You should have received a copy of the GNU Lesser General Public License
 *   along with Robot Playground. If not, see <http://www.gnu.org/licenses/>.
 */
package net.zarubsys.robotplayground.dummydevice.modules.obstacles;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.List;

import net.zarubsys.robotplayground.core.modules.IModuleConfiguration;

import org.apache.log4j.Logger;

/**
 * DummyObstaclesModuleConfiguration
 *
 * @author Lukas Zaruba, lukas.zaruba@gmail.com
 */
public class DummyObstaclesModuleConfiguration implements IModuleConfiguration {
	
	private static final long serialVersionUID = -167172624118913010L;
	
	public static final char EMPTY_FIELD = 'o';
	public static final char OBSTACLE_FIELD = 'x';
	
	private static final Logger LOG = Logger.getLogger(DummyObstaclesModuleConfiguration.class);
	
	private final File file;

	public DummyObstaclesModuleConfiguration(File file) {
		this.file = file;
	}

	public File getFile() {
		return file;
	}
	
	public static MapContainer loadMapFromFile(File mapFile) {
		List<BitSet> map = new ArrayList<>();
		int lineLength = -1;
		try (BufferedReader r = new BufferedReader(new FileReader(mapFile))) {
			String line;
			while ((line = r.readLine()) != null) {
				char[] charArray = line.toCharArray();
				if (lineLength < 0) {
					lineLength = charArray.length;
				}
				
				if (lineLength == 0 || charArray.length != lineLength) {
					throw new IllegalArgumentException("All lines in the file must be of the same length > 0!");
				}
				
				BitSet bitSet = createOneLine(charArray);
				map.add(bitSet);
			}
		} catch (IOException e) {
			LOG.error("Error while loading map from file '" + mapFile + "'!", e);
			throw new RuntimeException(e);
		}
		
		return new MapContainer(lineLength, map);
	}

	private static BitSet createOneLine(char[] charArray) {
		BitSet bitSet = new BitSet(charArray.length);
		for (int i = 0; i < charArray.length; i++) {
			char c = charArray[i];
			if (EMPTY_FIELD == c) {
				bitSet.set(i, false);
			} else if (OBSTACLE_FIELD == c) {
				bitSet.set(i, true);
			} else {
				throw new IllegalArgumentException("Map file must contain only 'o' or 'x' characters! Found '" + c + "'!");
			}
		}
		return bitSet;
	}

}

